interface KVRow {
  id: number
  key: string
  value: string
  valid: boolean
  isDefault: boolean
  hidden?: boolean
  readonly isEmpty?: boolean
  readonly isFull?: boolean
}

interface TableOptions {
  initialRows?: number;
  rows?: Array<Record<string, any>>;
}
export default class KeyValueTable {
  // rows: Array<Record<string, any>>= []
  // 使用接口明确定义行类型
  rows: Array<KVRow> = $state([])

  constructor(options: TableOptions = {}) {
    let {
      initialRows = 1,
      rows = [],
    } = options

    initialRows += rows.length
    this.rows = Array.from({ length: initialRows },
      (_, i) => {
        // 如果存在原始数据且当前索引在原始长度范围内
        if (rows && i < rows.length) {
          return this.createRow(rows[i]); // 处理现有行
        }
        return this.createRow(); // 创建新行
      }
    )
  }

  public isValidHeaderKey(key: string): boolean {
    // RFC 7230 规范的 HTTP 头验证
    if (!key.trim()) return true;
    return /^[A-Za-z0-9!#$%&'*+-.^_`|~]+$/.test(key);
  }

  private isValidKey(currentRow: KVRow): boolean {
    return !this.rows.some(row =>
      row.key === currentRow.key &&
      row.id !== currentRow.id // 排除自身
    );
  }


  private createRow(rowOption: Record<string, any> = {}): KVRow {
    let {
      id = Math.random(),
      key = "",
      value = "",
      isDefault = false,
      valid = true,
    } = rowOption

    return {
      id: id,
      key: key,
      value: value,
      isDefault: isDefault,
      valid: valid,
      get isEmpty() {
        return !this.key.trim() && !this.value.trim()
      },
      get isFull() {
        return !!this.key.trim() && !!this.value.trim()
      },
    }
  }

  private addRow() {
    this.rows = [...this.rows, this.createRow()]
  }


  public removeRow(id: number) {
    if (this.rows.length > 1) {
      this.rows = this.rows.filter((row) => row.id !== id)
      this.checkAutoAdd()
    }
  }

  public handleBlur(rowIndex: number) {
    const currentRow = this.rows[rowIndex]
    if (!this.isValidKey(currentRow)) {
      currentRow.value = `[键重复] ${currentRow.key}`
      currentRow.valid = false
      return
    }
    currentRow.valid = true
    if (currentRow.isEmpty) {
      if (rowIndex == this.rows.length - 1) return
      this.removeRow(currentRow.id)
    }

    this.checkAutoAdd()
  }

  private checkAutoAdd() {
    const lastRow = this.rows[this.rows.length - 1]
    if (lastRow.isFull) {
      this.addRow()
    }
  }

  get filledRows() {
    return this.rows.filter((row) => !row.isEmpty)
  }

  get keyValueObject() {
    return this.rows.reduce((acc, row) => {
      const key = row.key.trim()
      return row.isFull && row.valid ? { ...acc, [key]: row.value } : acc
    }, {})
  }
}
